<template>
  <BasicModal
    v-bind="$attrs"
    destoryOnClose
    width="40%"
    @register="registerModal"
    :title="getTitle"
    @open-change="visibleChangeHandler"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="tsx">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './flow-data';
  import { cloneDeep } from 'lodash-es';
  import { getRecipientsSchemaObj, getLimitObj } from './helper';
  import { useMessage } from '/@/hooks/web/useMessage';
  import SignatureModal from './SignatureModal.vue';
  import { useUserStore } from '/@/store/modules/user';
  const userStore = useUserStore();

  export default defineComponent({
    name: 'SendFlowModel',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register', 'cancel'],
    setup(_, { emit }) {
      const isSave = ref(true);
      const isManage = ref(false);
      const recipientsSchema = ref<any[]>([]);
      const receiverLimitMap = new Map<string, string[]>();
      const { createMessage } = useMessage();
      const [
        registerForm,
        {
          setFieldsValue,
          resetFields,
          validate,
          updateSchema,
          appendSchemaByField,
          removeSchemaByField,
        },
      ] = useForm({
        labelWidth: 100,
        baseColProps: { span: 24 },
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      let recipientsFieldArr;
      let SendFlowModelData;

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        console.log(
          '%cSendFlowModel===>54： ',
          'background: rgb(23, 197, 237,.6); color: #ff5023; font-size:18px;font-weight:700',
          data,
        );

        if (!SendFlowModelData || data.isSave != SendFlowModelData.isSave) {
          SendFlowModelData = data;
        }

        resetFields();
        removeSchemaByField(recipientsFieldArr);
        setModalProps({ confirmLoading: false });
        isSave.value = !!SendFlowModelData?.isSave;
        isManage.value = !!SendFlowModelData?.isManage;

        // 发送流程分申请人和审核人--通过审批意见(choices.length)判断；
        // 申请人保存--只显示申请名称可编辑；
        // 审核人保存--只显示申请名称不可编辑;
        // 申请人发送--显示申请名称可编辑，通过(receiverLimit.length)判断是否要显示选择审核人；
        // 审核人发送--显示审批意见单选，审批意见输入可编辑；通过(receiverLimit.length)判断是否要显示选择审核人；
        const recipientsSchemaObj = getRecipientsSchemaObj();

        if (SendFlowModelData.record) {
          const { choices, receiverLimit, activityVsFlag, verifySignatureUrl } =
            SendFlowModelData.record;

          const fieldSchemaArr = cloneDeep(formSchema);

          // 审核人
          if (choices.length) {
            const options = choices.map((item) => {
              return { label: item.name, value: item.id };
            });
            if (isSave.value) {
              console.log(' 审核人 保存');

              fieldSchemaArr.forEach((item) => {
                item.field === 'workItemName' &&
                  (item.componentProps = { ...item.componentProps, disabled: true });
                item.field === 'choices' && (item.ifShow = false);
                item.field === 'response' && (item.ifShow = false);
              });
            } else {
              console.log('审核人 发送', fieldSchemaArr);

              fieldSchemaArr.forEach((item) => {
                item.field === 'workItemName' && (item.ifShow = false);

                item.field === 'choices' &&
                  ((item.componentProps = { options }), (item.ifShow = true));

                item.field === 'response' && (item.ifShow = true);
              });
            }
          } else {
            // 申请人
            fieldSchemaArr.forEach((item) => {
              item.field === 'workItemName' && (item.ifShow = true);
              item.field === 'choices' && (item.ifShow = false);
              item.field === 'response' && (item.ifShow = false);
            });
          }

          // 点击发送--添加动态表单
          console.log(
            '!isSave.value && receiverLimit.length 点击发送--添加动态表单',
            isSave.value,
            !isSave.value && receiverLimit.length,
          );

          if (!isSave.value && receiverLimit.length) {
            recipientsSchema.value = receiverLimit.map((item) => {
              const choiceVal = choices[0] && choices[0].id;
              const limitObj = getLimitObj(
                choiceVal,
                {
                  ...item,
                  userInfo: userStore.getUserInfo,
                  record: data?.record?.formMap?.resultMap ?? {},
                },
                recipientsSchemaObj,
              );

              console.log('limitObj', limitObj);

              return limitObj;
            });

            recipientsFieldArr = recipientsSchema.value.map((item) => item?.field);
            console.log(
              '%c   recipientsSchema.value===>135： ',
              'background: rgb(23, 197, 237,.6); color: #ff5023; font-size:18px;font-weight:700',
              recipientsSchema.value,
            );

            appendSchemaByField(recipientsSchema.value, 'choices');
          }
          //  SendFlowModelData.guid
          // activityVsFlag
          // verifySignatureUrl
          // 发送时 是否需要电子签名
          if (!isSave.value && activityVsFlag === 1) {
            if (!verifySignatureUrl) return createMessage.error('未配置电子签名数据', 0.7);
            appendSchemaByField(
              {
                field: 'entryContent',
                label: '签名',
                itemProps: {
                  autoLink: false,
                },
                component: 'Input',
                rules: [{ required: true, message: '电子签名验证失败', type: 'object' }],
                render({ model, field }) {
                  return (
                    <SignatureModal
                      vModel={[model[field], 'value']}
                      guid={SendFlowModelData.guid}
                      url={verifySignatureUrl}
                    />
                  );
                },
              },
              'response',
            );
          }

          updateSchema(fieldSchemaArr);
          setFieldsValue({
            ...data.record,
            choices: choices[0] && choices[0].id,
          });
        }
      });

      const getTitle = computed(() => {
        if (unref(isSave)) {
          return '保存';
        } else {
          if (unref(isManage)) {
            return '审批';
          } else {
            return '申请';
          }
        }
      });

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          Object.keys(values).forEach((item) => {
            if (values[item] && /\d/.test(item)) {
              receiverLimitMap.set(item, values[item]);
            }
          });

          console.log('modelvalues', values, receiverLimitMap);
          closeModal();
          emit('success', values, {
            isSave: unref(isSave),
            receiverLimitMap,
            afterSumbitFn: SendFlowModelData.afterSumbitFn,
          });
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      function closeChooseModalHandle() {
        setModalProps({ open: true });
      }

      function visibleChangeHandler(val) {
        if (!val) {
          SendFlowModelData = undefined;
        }
      }

      return {
        registerModal,
        registerForm,
        getTitle,
        handleSubmit,
        closeChooseModalHandle,
        visibleChangeHandler,
      };
    },
  });
</script>
